package online.westonline.com.westonline.ui;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easy.west.westclient.Constants;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.utils.PicCrop;
import online.westonline.com.westonline.utils.ToastUtils;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 初始化头像选择activity
 */
public class AvatorActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{

    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.img_toolbar_menu)
    ImageView imgToolbarMenu;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ra_photo)
    RelativeLayout raPhoto;
    @BindView(R.id.ra_camera)
    RelativeLayout raCamera;
    private String img_url;

    @Override
    protected void initview() {
        //设置toolbar
        toolbar.setTitle("头像设置");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //初始化事件
        initsession();
    }

    private void initsession() {
        raPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkSdPermission();
            }
        });
        raCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkCameraPermission();
            }
        });
    }

    /**
     * 请求照相机权限
     */
    private void checkCameraPermission() {
        String[] permissions = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, permissions)) {
            //打开相册
            openCmaera();
        } else {
            EasyPermissions.requestPermissions(this, "申请读取相册权限", 10, permissions);
        }
    }

    /**
     * 请求相机权限
     */
    private void openCmaera() {
        PicCrop.cropFromCamera(this,PicCrop.config,PicCrop.TYPE_AVATAR);
    }

    /**
     * 请求sd卡权限
     */
    private void checkSdPermission() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, permissions)) {
            //打开相册
            openGrally();
        } else {
            EasyPermissions.requestPermissions(this, "申请读取相册权限", 10, permissions);
        }
    }

    /**
     * 打开相册
     */
    private void openGrally() {
        //打开相册裁剪
        //截取头像(圆)
       PicCrop.cropFromGallery(this,PicCrop.config,PicCrop.TYPE_AVATAR);
    }

    @Override
    protected void initdata() {

    }

    @Override
    protected int setlayout() {
        return R.layout.activity_avator;
    }

    /**
     * 修改返回键
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==android.R.id.home)
        {
            startActivity(HomeActivity.class,true);
        }
        return true;
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    //获取了裁剪后的图片,上传
    private void uploadAvator(Uri resultUri) {
        showProgessDialog("上传头像中请稍后");
        JMessageClient.updateUserAvatar(uri2File(resultUri), new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i==0)
                {
                    ToastUtils.showToast("头像上传成功");
                    startActivity(HomeActivity.class,true);
                    dissmissDialog();
                }
                else
                {
                    ToastUtils.showToast("头像上传失败:"+s);
                    dissmissDialog();
                }
            }
        });
    }

    /**
     * uri转回file
     * @param uri
     * @return
     */
    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }


    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @return content Uri
     */
    public static Uri getImageContentUri(Context context,String url) {
        File file = new File(url);
        if (url.contains(Constants.My_AVATOR))
        {
            //是保存路径
            File file1 = new File(url,"my_avator.png");
            //创建新文件
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (!file.exists())
        {
            file.mkdirs();
        }

        String filePath =file.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (file.exists())
            {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode()==KeyEvent.KEYCODE_BACK)
        {
            startActivity(HomeActivity.class,true);
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        PicCrop.onActivityResult(requestCode, resultCode, data, this, new PicCrop.CropHandler() {
            @Override
            public void handleCropResult(Uri uri, int tag) {
                Log.e("裁剪消息","成功");
                //更新头像
                uploadAvator(uri);
            }

            @Override
            public void handleCropError(Intent data) {
                Log.e("裁剪消息","失败");
            }
        });
    }
}
